//
//  MessageCircleDetailViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/7.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
import Networking
import SnapKit

class MessageCircleDetailViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, MessageCircleDetailHeaderViewDelegate, AddCornerUIRectCorner {
    @IBOutlet weak var mainTableView: UITableView!
    
    var circieId: String?
    var data: CircleDetailModel?
    var dataArr: [circleDetailListModel] = []
    private var headerView = MessageCircleDetailHeaderView().instanceMessageCircleDetailHeaderView()
    var floatButton: UIButton!
    let notiName:String = "circleReloadCell"
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var indexPath :IndexPath?
    var backView: UIView?
    var isShow: Bool = false
    var contaner: UIView?
    var page: Int = 0
    var totalPage:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        isShow = false
        setNavigationColor(colorState: .black)
        setUI()
        self.navigationItem.rightBarButtonItem = nil
        self.fetchCircleDetail()
        NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name:NSNotification.Name(rawValue: notiName), object: nil)
    }
    
    @objc private func notificationAction(noti: Notification) {
        if noti.object == nil {
            return
        }
        if indexPath != nil {
            var model:circleDetailListModel = self.dataArr[(self.indexPath?.row)!]
            if noti.object is VideoModel {
                let ar:VideoModel = noti.object as! VideoModel
                model.collected = ar.collected
                model.favorite = ar.favorite
                model.comment = ar.comment
                self.dataArr[(self.indexPath?.row)!] = model
                self.mainTableView.reloadRows(at: [self.indexPath!], with: UITableViewRowAnimation.automatic)
            }else {
                let ar:ArticleModel = noti.object as! ArticleModel
                model.collected = ar.collected
                model.favorite = ar.favorite
                model.comment = ar.comment
                self.dataArr[(self.indexPath?.row)!] = model
                self.mainTableView.reloadRows(at: [self.indexPath!], with: UITableViewRowAnimation.automatic)
            }
        }
        
    }
    
    func setUI() {
        mainTableView.register(UINib(nibName: "\(MessageCircleDetailTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        headerView.delegate = self
        
//        headerView.autoresizingMask = .init(rawValue: 0)
        mainTableView.tableHeaderView = headerView
        mainTableView.estimatedRowHeight = 100
        mainTableView.rowHeight = UITableViewAutomaticDimension
        
        self.mainTableView.tableHeaderView = headerView
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        mainTableView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        
        self.floatButton = UIButton(type:.custom)
        self.floatButton? .setImage(UIImage(named:"left_my_creation"), for: .normal)

        self.floatButton?.backgroundColor = UIColor.white
        UIApplication.shared.keyWindow?.addSubview(self.floatButton)
        self.floatButton.snp.makeConstraints { (make) -> Void in
            make.width.height.equalTo(60)
            make.right.equalTo(UIApplication.shared.keyWindow!).offset(-20)
            make.bottom.equalTo(UIApplication.shared.keyWindow!).offset(-150)
        }
        self.floatButton.addTarget(self, action: #selector(tappedButton), for: .touchUpInside)
        self.view.setNeedsUpdateConstraints()
        self.view.updateFocusIfNeeded()
        
        
        let container = UIView()
        container.backgroundColor = UIColor.black
        self.contaner = container
        UIApplication.shared.keyWindow?.addSubview(container)
        container.snp.makeConstraints { (make) -> Void in
            make.width.height.equalTo(40)
            make.center.equalTo(self.floatButton)
        }
//        container.width = 40
//        container.height = 40
//        container.center = self.floatButton.center
//        addCornerWithView(aView: container, aCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight], aSize: CGSize(width: 20, height: 20))
        UIApplication.shared.keyWindow?.bringSubview(toFront: self.floatButton)
        self.contaner?.alpha = 0
        isShow = false
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.floatButton.layer.masksToBounds = true
        self.floatButton.layer.cornerRadius = 30
        self.contaner?.layer.masksToBounds = true
        self.contaner?.layer.cornerRadius = 20
    }
    override func viewWillAppear(_ animated: Bool) {
        self.floatButton.isHidden = false
        self.contaner?.isHidden = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        self.floatButton.isHidden = true
        self.contaner?.isHidden = true
    }
    @objc func tappedButton(){
        
        if isShow {
            self.contaner?.height = 40
            let y: CGFloat = (self.contaner?.y)!
            self.contaner?.y = y + 80
            self.contaner?.alpha = 0
            isShow = false
            self.backView?.removeFromSuperview()
            return
        }
        
        isShow = true
        let view = UIView()
        view.backgroundColor = UIColor.gray
        view.alpha = 0.3
        self.navigationController?.view.addSubview(view)
//        UIApplication.shared.keyWindow?.insertSubview(view, belowSubview: self.contaner!)
        
        view.frame = UIScreen.main.bounds
        let tap = UITapGestureRecognizer(target: self, action: #selector(tap(tap:)))
        view.addGestureRecognizer(tap)
        self.backView = view
        
//        self.view.bringSubview(toFront: self.contaner!)
//        self.view.bringSubview(toFront: self.floatButton)
        
        let frame: CGRect = (self.contaner?.frame)!
       
        UIView.setAnimationsEnabled(true)
        UIView.animate(withDuration: 0.5, animations: {
//            self.contaner?.height = 120
//            self.contaner?.y = y - 80
            self.contaner?.frame = CGRect(x: frame.origin.x, y: frame.origin.y - 82, width: frame.size.width, height: 120)
            self.contaner?.alpha = 1
        }) { (boo) in
            var y: CGFloat = 0
            for i in 0 ..< 2 {
                let btn = UIButton(type: .custom)
                btn.backgroundColor = UIColor.white
                if i == 1 {
                   btn.setImage(UIImage(named: "send_video"), for: .normal)
                }else {
                    btn.setImage(UIImage(named: "send_article"), for: .normal)
                }
                
                btn.x = 0
                btn.y = y
                btn.width = 40
                btn.height = 40
                btn.tag = 100 + i
                self.contaner?.addSubview(btn)
                y += 40
                btn.addTarget(self, action: #selector(self.tapBtn(btn:)), for: .touchUpInside)
            }
        }
        
    }
    
    @objc func tap(tap: UIGestureRecognizer?){
        self.contaner?.height = 40
        let y: CGFloat = (self.contaner?.y)!
        self.contaner?.y = y + 80
        self.contaner?.alpha = 0
        isShow = false
        self.backView?.removeFromSuperview()
    }
    
    @objc func tapBtn(btn: UIButton){
        self.tap(tap: nil)
        if !MineInfoModel.share.isLogin {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(loginVC, animated: true)
            return
        }
        switch btn.tag - 100 {
        case 0:
            let richTextEditViewController = PublishViewController(nibName: "PublishViewController", bundle: nil)
            let mainNavigation = MainNavigaionViewController(rootViewController: richTextEditViewController)
            
            self.present(mainNavigation, animated: true, completion: nil)
            
        case 1:
            let richTextEditViewController = PublishViewController(nibName: "PublishViewController", bundle: nil)
            richTextEditViewController.isVideo = true
            let mainNavigation = MainNavigaionViewController(rootViewController: richTextEditViewController)
            self.present(mainNavigation, animated: true, completion: nil)
            
        default:break
        }
    }
    
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        self.fetchCircleTable(parameters: ["page":page,"pageSize":10,"type":2])
    }
    
    
     /// 获取圈子列表
    func fetchCircleDetail() -> Void {
       let requesturl = "\(BaseURL)\(circleDetailUrl)" + "/" + circieId!
        Alamofire.request(requesturl, method: .get,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                        let dataTemp = json["data"].dictionary!

                                        var data1 = CircleDetailModel(fromDic: dataTemp)
                                        data1.initCircleUsers(arr: (dataTemp["circleUsers"]?.array)!)
                                        data1.initLabelCircleUserForApp(arr: (dataTemp["circleUserForApp"]?.array)!)
                                        
                                        self.data = data1
                                        self.headerView.bindData(data: data1)
                                        
                                        
                                        self.mainTableView.beginUpdates()
                                        self.mainTableView.tableHeaderView = self.headerView
                                        self.mainTableView.endUpdates()
                                        DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute:
                                            {
                                                self.headerRefresh()
                                        })
                                        

                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{

                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                            }
        }
    }
    
    /// 获取圈子动态
    func fetchCircleTable(parameters:[String:Any]) -> Void {
        
        let requesturl = "\(BaseURL)\(circleDetailTabUrl)" + "/" + circieId!
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!

                                        if self.page == 1{
                                            self.dataArr.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = circleDetailListModel(fromDic: dic)

                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthorModel(dic: (author?.dictionary!)!)
                                            }
                                            
                                            let label = dic["label"]
                                            if !(label?.isEmpty)!{
                                                model.initLabel(dic: (label?.dictionary!)!)
                                            }

                                            self.dataArr.append(model)
                                        }
                                        if self.totalPage == self.dataArr.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()

                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                                self.showToast(msg:"请求失败")
                            }
        }
    }
    
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? MessageCircleDetailTableViewCell
        let model: circleDetailListModel? = self.dataArr[indexPath.row]
        cell?.bindData(data: model)
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.indexPath = indexPath
        let model1: circleDetailListModel = self.dataArr[indexPath.row]
        var model: BannerModel = BannerModel()
        model.id = model1.id
        model.type = model1.redirectType
        model.url = model1.share
        model.coverPath = model1.coverImgPath
        model.notiname = self.notiName
        self.bannerJump(model: model)
    }
    
    // MARK: - MessageCircleDetailHeaderViewDelegate
    func memberTap() {
        let messageCircleMemberVC = MessageCircleMemberViewController(nibName: "\(MessageCircleMemberViewController.self)", bundle: nil)
        messageCircleMemberVC.titleLabel(text: "圈子成员", nil)
        messageCircleMemberVC.circieId = self.circieId
        self.navigationController?.pushViewController(messageCircleMemberVC, animated: true)
    }
    
    func headerTap() {
        let messageCirclePersonalCenterVC = PersonInfoViewController(nibName: "\(PersonInfoViewController.self)", bundle: nil)
        messageCirclePersonalCenterVC.userId = (data?.id!)!
        self.navigationController?.pushViewController(messageCirclePersonalCenterVC, animated: true)
    }
    
    func followAc(id:String,btn:UIButton) -> Void {
        var requesturl = "\(BaseURL)\(circleJoinUrl)"
        if btn.isSelected {
            requesturl = "\(BaseURL)\(circleOutUrl)"
        }
        let parameters:[String:Any] = ["circleId": id]
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.headerView.followButton.isSelected = !(self.headerView.followButton.isSelected)
                                        self.showToast(msg:json["message"].string!)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                            }
        }
    }
    
    func delCell(id:String,cell:ShoppingCartTableViewCell) -> Void {
        let alertController = UIAlertController(title: "删除商品？", message: nil, preferredStyle: .alert)
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: { (_) in
            
        })
        let sureAction = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
            let url = appendUrl(suffix: delCar)
            let parameter:[String : String] = ["id": id]
            Alamofire.request(url, method: .get,
                              parameters: parameter,
                              encoding: URLEncoding.default,
                              headers: nil).responseJSON {
                                (response) in
                                
                                if(response.error == nil){
                                    if let result = response.result.value as? NSDictionary
                                    {
                                        
                                        let json = JSON(result)
                                        if json["code"].int == 1{
                                            self.showToast(msg:json["message"].stringValue)
                                            cell.deleteblock!()
                                        }
                                        else{
                                            self.showToast(msg:json["message"].stringValue)
                                        }
                                    }
                                }else{
                                    self.showToast(msg:"删除失败")
                                }
                                
            }
        })
        alertController.addAction(cancel)
        alertController.addAction(sureAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
